package com.mm.cloth;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;

import com.bumptech.glide.Glide;
import com.mm.cloth.model.Clothes;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class AddClothesActivity extends AppCompatActivity {

    private static final int REQUEST_IMAGE_PICK = 1001;
    
    // UI组件
    private ImageView ivPreview;
    private ImageView ivDelete;
    private LinearLayout layoutUpload;
    private SwitchCompat switchMatting;
    private EditText etName;
    private TextView tvCategory;
    private TextView tvSeason;
    private EditText etBrand;
    private EditText etPrice;
    private TextView tvDate;
    private EditText etNotes;
    
    // 数据
    private Uri imageUri;
    private String selectedCategory = "";
    private String selectedCategoryId = "";
    private String selectedSeason = "";
    private Calendar calendar;
    
    // 分类和季节数据
    private String[] categories = {"上衣", "裤子", "裙子", "外套", "鞋子", "配饰"};
    private String[] categoryIds = {"tops", "pants", "skirts", "outerwear", "shoes", "accessories"};
    private String[] seasons = {"春季", "夏季", "秋季", "冬季", "四季"};
    private String[] seasonIds = {"spring", "summer", "autumn", "winter", "all"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_clothes);
        
        // 设置返回按钮
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("添加衣物");
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        
        // 初始化日期选择器
        calendar = Calendar.getInstance();
        
        initViews();
        setupListeners();
    }
    
    private void initViews() {
        ivPreview = findViewById(R.id.ivPreview);
        ivDelete = findViewById(R.id.ivDelete);
        layoutUpload = findViewById(R.id.layoutUpload);
        switchMatting = findViewById(R.id.switchMatting);
        etName = findViewById(R.id.etName);
        tvCategory = findViewById(R.id.tvCategory);
        tvSeason = findViewById(R.id.tvSeason);
        etBrand = findViewById(R.id.etBrand);
        etPrice = findViewById(R.id.etPrice);
        tvDate = findViewById(R.id.tvDate);
        etNotes = findViewById(R.id.etNotes);
        
        // 设置保存按钮点击事件
        Button btnSave = findViewById(R.id.btnSave);
        btnSave.setOnClickListener(v -> saveClothes());
    }
    
    private void setupListeners() {
        // 上传图片点击事件
        layoutUpload.setOnClickListener(v -> openImagePicker());
        
        // 删除图片点击事件
        ivDelete.setOnClickListener(v -> {
            imageUri = null;
            ivPreview.setVisibility(View.GONE);
            ivDelete.setVisibility(View.GONE);
            layoutUpload.setVisibility(View.VISIBLE);
        });
        
        // 分类选择点击事件
        findViewById(R.id.layoutCategory).setOnClickListener(v -> showCategoryDialog());
        
        // 季节选择点击事件
        findViewById(R.id.layoutSeason).setOnClickListener(v -> showSeasonDialog());
        
        // 日期选择点击事件
        findViewById(R.id.layoutDate).setOnClickListener(v -> showDatePicker());
    }
    
    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_IMAGE_PICK);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK && data != null) {
            imageUri = data.getData();
            if (imageUri != null) {
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
                    ivPreview.setImageBitmap(bitmap);
                    ivPreview.setVisibility(View.VISIBLE);
                    ivDelete.setVisibility(View.VISIBLE);
                    layoutUpload.setVisibility(View.GONE);
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(this, "加载图片失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
    
    private void showCategoryDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择分类");
        builder.setItems(categories, (dialog, which) -> {
            selectedCategory = categories[which];
            selectedCategoryId = categoryIds[which];
            tvCategory.setText(selectedCategory);
            tvCategory.setTextColor(getResources().getColor(android.R.color.black));
        });
        builder.show();
    }
    
    private void showSeasonDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择季节");
        builder.setItems(seasons, (dialog, which) -> {
            selectedSeason = seasonIds[which];
            tvSeason.setText(seasons[which]);
            tvSeason.setTextColor(getResources().getColor(android.R.color.black));
        });
        builder.show();
    }
    
    private void showDatePicker() {
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, year, month, dayOfMonth) -> {
                    calendar.set(Calendar.YEAR, year);
                    calendar.set(Calendar.MONTH, month);
                    calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    updateDateLabel();
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        );
        datePickerDialog.show();
    }
    
    private void updateDateLabel() {
        String dateFormat = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.getDefault());
        tvDate.setText(sdf.format(calendar.getTime()));
        tvDate.setTextColor(getResources().getColor(android.R.color.black));
    }
    
    private void saveClothes() {
        // 验证输入
        if (imageUri == null) {
            Toast.makeText(this, "请上传衣物图片", Toast.LENGTH_SHORT).show();
            return;
        }
        
        String name = etName.getText().toString().trim();
        if (name.isEmpty()) {
            etName.setError("请输入衣物名称");
            etName.requestFocus();
            return;
        }
        
        if (selectedCategoryId.isEmpty()) {
            Toast.makeText(this, "请选择分类", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (selectedSeason.isEmpty()) {
            Toast.makeText(this, "请选择季节", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 获取其他字段
        String brand = etBrand.getText().toString().trim();
        String priceStr = etPrice.getText().toString().trim();
        double price = 0.0;
        if (!priceStr.isEmpty()) {
            try {
                price = Double.parseDouble(priceStr);
            } catch (NumberFormatException e) {
                etPrice.setError("请输入有效的价格");
                etPrice.requestFocus();
                return;
            }
        }
        
        String purchaseDate = tvDate.getText().toString();
        String notes = etNotes.getText().toString().trim();
        boolean autoMatting = switchMatting.isChecked();
        
        // 模拟上传图片和保存数据
        // 实际应用中，这里应该调用网络请求上传图片并保存数据
        Toast.makeText(this, "正在保存...", Toast.LENGTH_SHORT).show();
        
        // 模拟网络请求
        new Thread(() -> {
            try {
                // 模拟网络延迟
                Thread.sleep(1500);
                
                // 返回主线程更新UI
                runOnUiThread(() -> {
                    Toast.makeText(AddClothesActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                    finish(); // 关闭当前页面，返回上一页
                });
                
            } catch (InterruptedException e) {
                e.printStackTrace();
                runOnUiThread(() -> {
                    Toast.makeText(AddClothesActivity.this, "保存失败，请重试", Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }
    
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed(); // 处理返回按钮点击
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
} 